<?php
class AuthController extends Controller
{
	public function init(){

	}

	public function actions()
	{
		return array(
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	public function actionIndex(){
		$this->forward('/auth/login');	
	}

	public function actionRegister(){
		//check if logged in or not?
		if(!Yii::app()->user->isGuest){
			Yii::app()->request->redirect(Yii::app()->user->returnUrl);
		}
		//do register
		if(Yii::app()->request->isPostRequest)
		{
			try{
				$args = array(
					'user_username' => Yii::app()->request->getPost('email', null),
					'user_email' => Yii::app()->request->getPost('email', null),
					'user_password' => Yii::app()->request->getPost('password', null),
					'user_fullname' => 	Yii::app()->request->getPost('fullname', null),
					'user_status' => 1
				);
				//TODO: CHECK EMAIL
				//create user
				$userId = Users::getInstance()->insert($args);
				if($userId){
					//create profile
					Users::getInstance()->insertProfile($userId, array(
						'profile_status' => 1
					));
					//add user to deafault role (members)
					Roles::getInstance()->updateUserRole($userId, 3);
					//done
					Yii::app()->user->setFlash('ok', "Your account has been created successfully! Please login to continue");
				} else {
					Yii::app()->user->setFlash('error', "An error has occurred. Please contact your system administrator");
				}
				//redirect to login page
				$this->redirect('/auth/login'); exit;
			} catch (Exception $ex){
				Yii::app()->user->setFlash('error', "Sorry, this email already exists. Please choose another one or login to continue");
				$this->refresh();
			}
		}
		//render layout
		if(Yii::app()->request->isAjaxRequest)
			$this->renderPartial('register');
		else
			$this->render('register');
	}

	public function actionLogin(){
		//check if logged in or not?
		if(!Yii::app()->user->isGuest){			
			Yii::app()->request->redirect(Yii::app()->user->returnUrl);
		}
		//do login
		if(Yii::app()->request->isPostRequest)
		{
			$email = Yii::app()->request->getParam('email', null);
			$password = Yii::app()->request->getParam('password', null);
			//check valid email?			
			if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
				Yii::app()->user->setFlash('error', Yii::t('common', 'Login failed because email or password is incorrect'));
			}
			try{
				$identity = new UserIdentity($email,$password);
				if($identity->authenticate()){
					//login successfully, Keep the user logged in for 1 hours (Make sure allowAutoLogin is set true for the user component)
					Yii::app()->user->login($identity, 3600);
					
					//write log
					Logs::getInstance()->insert(array(
						'user_id' => Yii::app()->user->id,
						'user_ip' => Utils::getIp(),
						'user_agent' => $_SERVER['HTTP_USER_AGENT'],
						'log_action' => 'USER_LOGIN',
						'log_message' => '<b>'.Yii::app()->user->getState('fullname').'</b> logged in'
					));
					
					//redirect
					$redirectUrl = urldecode(Yii::app()->request->getParam('url', null));
					if(empty($redirectUrl)) $redirectUrl = Yii::app()->request->baseUrl;
					$this->redirect($redirectUrl);
					exit;
				}
				else{						
					//write log
					Logs::getInstance()->insert(array(
						'user_id' => null,
						'user_ip' => Utils::getIp(),
						'user_agent' => $_SERVER['HTTP_USER_AGENT'],
						'log_action' => 'USER_LOGIN',
						'log_message' => '<b>'.$email.'</b> (IP: '.Utils::getIp().') login fail'
					));
					
					//wrong credentials 
					//echo $identity->errorMessage;
					Yii::app()->user->setFlash('error', Yii::t('common', 'Login failed because email or password is incorrect'));
					
					//refresh
					$this->refresh();
					exit;
				}
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', $ex->getMessage());
				$this->refresh();
			}
		}
		//render layout
		if(Yii::app()->request->isAjaxRequest)
			$this->renderPartial('login');
		else
			$this->render('login');
	}
	
	public function actionLoginFb(){
		//check if logged in or not?
		if(!Yii::app()->user->isGuest){
			Yii::app()->request->redirect(Yii::app()->user->returnUrl);
		}
		
		require_once 'facebook-php-sdk/autoload.php';		
		require_once 'facebook-php-sdk/src/Facebook/FacebookSession.php';
		require_once 'facebook-php-sdk/src/Facebook/FacebookRequest.php';
		require_once 'facebook-php-sdk/src/Facebook/GraphObject.php';
		require_once 'facebook-php-sdk/src/Facebook/GraphUser.php';
		require_once 'facebook-php-sdk/src/Facebook/FacebookSDKException.php';
		require_once 'facebook-php-sdk/src/Facebook/FacebookRequestException.php';

		Facebook\FacebookSession::setDefaultApplication(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET);
		$helper = new Facebook\FacebookRedirectLoginHelper(BASE_URL.'/auth/loginfb');
		try{
			$session = $helper->getSessionFromRedirect();			
		}catch(Facebook\FacebookRequestException $ex) {
			// When Facebook returns an error
			error_log($ex);
			$session = null;
		}catch(\Exception $ex) {
			// When validation fails or other local issues
			error_log($ex);
			$session = null;
		}

		$fbUser = array();
		if(isset($session)) {
			// Logged in & retrieve facebook user infromation
			$me = (new Facebook\FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(Facebook\GraphUser::className());
			$fbUser = array(
				'id' => $me->getProperty('id'),
				'email' => $me->getProperty('email'),
				'first_name' => $me->getProperty('first_name'),
				'middle_name' => $me->getProperty('middle_name'),
				'last_name' => $me->getProperty('last_name'),
				'name' => $me->getProperty('name'),
				'gender' => $me->getProperty('gender'),
				'link' => $me->getProperty('link'),
				'locale' => $me->getProperty('locale'),
				'timezone' => $me->getProperty('timezone'),
				'updated_time' => $me->getProperty('updated_time'),
				'verified' => $me->getProperty('verified'),
			);
		}
		else {
			$loginUrl = $helper->getLoginUrl(array(
				'scope' => 'email'
			));
			header("Location: ".$loginUrl); exit;
		}

		//Login with facebook
		if (!empty($fbUser)) {
			try {
				$provider = 'facebook';
				$user = Users::getInstance()->getOauthUser($fbUser['id'], $provider);
				//register
				if(empty($user)){					
					//insert to db
					$userId = Users::getInstance()->insert(array(
						'user_username' => $fbUser['id'],
						'user_email' => $fbUser['email'],
						'user_fullname' => $fbUser['name'],
						'user_password' => '',
						'user_verified' => $fbUser['verified'],
						'user_status' => 1,
						'oauth_provider' => $provider,
						'oauth_uid' => $fbUser['id']
					));
					//create profile
					Users::getInstance()->insertProfile($userId, array(
						'profile_firstname' => $fbUser['first_name'],
						'profile_middlename' => $fbUser['middle_name'],
						'profile_lastname' => $fbUser['last_name'],						
						'profile_image' => "https://graph.facebook.com/{$fbUser['id']}/picture",
						'profile_gender' => ($fbUser['first_name']=='male')?1:($fbUser['first_name']=='female')?0:null,
						'profile_timezone' => $fbUser['timezone'],
						'profile_status' => 1
					));
					//get user info
					$user = Users::getInstance()->getOauthUser($fbUser['id'], $provider);
				}
				//auto logged in
				$identity = new UserIdentity($user['user_username'], '');
				if($identity->authenticate()){
					Yii::app()->user->login($identity);	
					Yii::app()->request->redirect(Yii::app()->user->returnUrl);
				}
			} catch (Exception $ex) {
				echo $ex->getMessage(); die;
				error_log($ex);
			}
		} else {
			Yii::app()->user->setFlash('error', 'Unknown error occurred while connecting to facebook');
			$this->refresh();
		}
	}

	public function actionLogout()
	{
		//check if logged in or not?
		if(Yii::app()->user->isGuest){
			Yii::app()->request->redirect(Yii::app()->user->returnUrl);
		}
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}